// src/api/axios.js
import axios from 'axios';
import { getToken } from '../utils/storage';

// Create Axios instance with default config
const axiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_URL || 'https://api.example.com',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  }
});

// Request interceptor to add auth token to all requests except login and register
axiosInstance.interceptors.request.use(
  (config) => {
    const token = getToken();
    const isAuthEndpoint = 
      config.url.includes('/login') || 
      config.url.includes('/register');
    
    if (token && !isAuthEndpoint) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// Response interceptor to handle common errors
axiosInstance.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    // Handle unauthorized errors (401) - token expired or invalid
    if (error.response && error.response.status === 401) {
      // Redirect to login page or refresh token
      window.location.href = '/login';
    }
    
    return Promise.reject(error);
  }
);

export default axiosInstance;